package com.zhuxin.medical.mvc.controller;

import com.CommWxApplication;
import com.dbHelper.DbTemplate;
import com.soecode.wxtools.api.WxService;
import com.soecode.wxtools.bean.KeyWord;
import com.soecode.wxtools.bean.TemplateSender;
import com.soecode.wxtools.bean.result.TemplateSenderResult;
import com.soecode.wxtools.exception.WxErrorException;
import com.zhuxin.common.BussResp;
import com.zhuxin.common.UtilTools;
import com.zhuxin.medical.model.po.*;
import com.zhuxin.medical.mvc.service.CommWxSerivce;
import org.apache.commons.lang3.ArrayUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by lzb on 2018/9/18.
 */
@RestController
@RequestMapping("/wx")
public class WxCtr {

    private static final Logger log = LoggerFactory.getLogger(WxCtr.class);


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CommWxSerivce serivce;

    @Autowired
    private DbTemplate oracleDao;

    @Autowired
    private DbTemplate mysqlDao;

    @Autowired
    private WxService wxService;

    @Value("${wx.appId}")
    private String appid;
    @Value("${wx.appSecret}")
    private String appSecret;

    private Set<String> pc=new HashSet<>(100);

    @RequestMapping("/getUserImf")
    @ResponseBody
    public String getUserImf(String code, HttpServletResponse response) throws Exception {
        String result=null;
//        if(UtilTools.isNullOrBlank(code)){
//            String url=anthUrl;
//            url=UtilTools.replaceStr(url,"{0}",appid);
//            url=UtilTools.replaceStr(url,"{1}","http://e22v638378.imwork.net/wx/getUserImf");
//            response.sendRedirect(url);
//        }else{
//            log.info("code:{}",code);
//            if(pc.add(code)) {
//                try {
//                    String url = userinfUrl;
//                    url = UtilTools.replaceStr(url, "{0}", appid);
//                    url = UtilTools.replaceStr(url, "{1}", appSecret);
//                    url = UtilTools.replaceStr(url, "{2}", code);
//                    String tkstr = restTemplate.getForObject(url, String.class);
//                    log.info("第二次回调参数" + tkstr);
//                    JSONObject json = new JSONObject(tkstr);
//                    String token = json.getString("access_token");
//                    String openid = json.getString("openid");
//                    url = userinfoUrl;
//                    url = UtilTools.replaceStr(url, "{0}", token);
//                    url = UtilTools.replaceStr(url, "{1}", openid);
//                    result = restTemplate.getForObject(url, String.class);
//                    log.info(result);
                    result= (String) CommWxApplication.threadMap.get().get("result");
                    if(result!=null)this.serivce.saveUserinfo(result);//人员信息入库
//                } finally {
//                    pc.remove(code);
//                }
//            }
//        }
        return "采花完成，谢谢支持~";
    }


//    @RequestMapping("/WxCancelPlan")
//    @ResponseBody
//    public BussResp WxCancelPlan(HttpServletRequest request, HttpServletResponse response){
//        //权限校验
//        List<CommWxUser> user = this.mysqlDao.querySub("select * from commWxUser where openid=? and usertype=1", CommWxApplication.threadMap.get().get("openid"), CommWxUser.class);
//        if(user.isEmpty())return BussResp.createResp("This operation is fail,Lack of authority!!!");
//        try{
//            String infoId = request.getParameter("infoId");
//            //String confirm = request.getParameter("confirm");
////            CoPlanCanelinfo caInfo = new CoPlanCanelinfo();
////            caInfo.setId(Long.valueOf(infoId));
////            caInfo=this.oracleDao.queryVoByKey(caInfo);
//            CommAppLog log=new CommAppLog();
//            log.setRecid(infoId);
//            log=this.mysqlDao.queryVoByKey(log);
//            String[] yjplanguids = log.getPlanids().split(",");
//            for(String yjplanguid : yjplanguids){
//                CoRuPlan pkVO = new CoRuPlan();
//                pkVO.setYjplanid(Long.valueOf(yjplanguid));
//                pkVO.setStatus(-1L);
//                this.oracleDao.updateSub(pkVO,"status",true);
//            }
//            log.setStatus(3L);
//            log.setApproveid(user.get(0).getOpenid());
//            log.setApprover(user.get(0).getUsercode());
//            log.setApprovetime(new Date());
//            this.mysqlDao.updateSub(log, ArrayUtils.toArray("status","Approveid","approver","Approvetime"),true);
//            user.get(0).setStatus(0);
//            this.mysqlDao.updateSub(user.get(0),"status",true);
//            return BussResp.createResp("This operation is Success");
//        }catch(Exception e){
//            return BussResp.createResp("This operation is fail"+e.getMessage());
//        }
//    }

    @RequestMapping("/test")
    @ResponseBody
    public BussResp test(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Integer integers = this.oracleDao.queryForObjectExt("select count(*) from co_ru_plan ", Integer.class);
        return BussResp.createResp(integers);
    }
    @RequestMapping("/test2")
    @ResponseBody
    public void test2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //WxService wxService = ;
        TemplateSender sender = new TemplateSender();
        sender.setTouser("oqcqkw2WuZIsEHKjqwX80ck-VFrw");
        sender.setTemplate_id("TFJPk9Hjq0nYCGZrcV8SfdGa_mFS8kn--LXkWIXvg6o");
        CoWxTemplateInfo info = new CoWxTemplateInfo();
        info.setFirst(new KeyWord("您有一个新的报修申请需要处理"));
        info.setKeyword1(new KeyWord("手机申报"));
        info.setKeyword2(new KeyWord("电脑不能上网"));
        info.setKeyword3(new KeyWord("张三"));
        info.setKeyword4(new KeyWord("12354323454"));
        info.setKeyword5(new KeyWord(new Date().toString()));
        info.setRemark(new KeyWord("111111"));
        sender.setData(UtilTools.object2Map(info));
        //sender.setUrl("url");
        try {
            TemplateSenderResult result = wxService.templateSend(sender);
            System.out.println(result.toString());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }

    public static final String userinfoUrl="https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
    public static final String userinfUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
    public static final String anthUrl="https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
}
